﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SGP;
using System.Xml.Linq;

namespace AnimationTool
{
    public partial class Form1 : Form
    {
        Timer animationTime = new Timer();
        int frameCount;
        public bool run;
        string workspace;

        bool mouseDrag = false;
        bool indexChange = false;
        Point mousePos;
        Point mouseDown;
        Point mouseUp;
        Point offset1;
        int type;

        public Form1()
        {
            InitializeComponent();
            SGP.ManagedDirect3D.Instance.InitManagedDirect3D(pictureBox1, true);
            SGP.ManagedDirect3D.Instance.InitManagedDirect3D(pictureBox2, true);
            SGP.ManagedTextureManager.Instance.InitManagedTextureManager(
                SGP.ManagedDirect3D.Instance.Device, SGP.ManagedDirect3D.Instance.Sprite);

            animationTime.Tick += new EventHandler(animationTime_tick);

            workspace = "None";
            frameCount = 0;
            type = 0;

            run = true;
        }

        public void CloseForm1(object sender, EventArgs e)
        {
            run = false;
        }

        void animationTime_tick(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];

                if (frameCount >= frameList.Items.Count - 1)
                {
                    frameList.SelectedIndex = 0;
                    frameCount = 0;

                    if (!tmp.isLooping)
                    {
                        animationTime.Stop();
                        groupBox5.Enabled = true;
                        groupBox6.Enabled = true;
                        AnimationGroup.Enabled = true;
                        FrameGroup.Enabled = true;
                        ResetButton.Enabled = true;
                        NextFrameButton.Enabled = true;
                        PrevFrameButton.Enabled = true;
                    }
                }
                else
                {
                    ++frameList.SelectedIndex;
                    Frame tmpFrame = tmp.frameList[++frameCount];
                    animationTime.Interval = (int)(1000 * tmpFrame.frameDelay / tmp.playSpeed);
                }
            }
        }

        public void Render()
        {
            if (animationList.SelectedIndex != -1)
            {
                Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
                if (tmp.spriteSheetID != -1)
                {
                    if (SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID) < pictureBox1.Height)
                        pictureBox1.Height = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);

                    if (SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID) < pictureBox1.Width)
                        pictureBox1.Width = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);

                    vScrollBar1.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID) - pictureBox1.Height;
                    hScrollBar1.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID) - pictureBox1.Width;

                    if (hScrollBar1.Maximum <= 0)
                        hScrollBar1.Visible = false;
                    else
                        hScrollBar1.Visible = true;

                    if (vScrollBar1.Maximum <= 0)
                        vScrollBar1.Visible = false;
                    else
                        vScrollBar1.Visible = true;

                    offset1.X = hScrollBar1.Value;
                    offset1.Y = vScrollBar1.Value;

                    if (offset1.X < 0)
                        offset1.X = 0;

                    if (offset1.Y < 0)
                        offset1.Y = 0;

                    ImageTopRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);
                    ImageBottomRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);
                    ImageLeftRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);
                    ImageRightRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);

                    ColTopRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);
                    ColBottomRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);
                    ColLeftRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);
                    ColRightRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);

                    ActiveTopRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);
                    ActiveBottomRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureHeight(tmp.spriteSheetID);
                    ActiveLeftRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);
                    ActiveRightRect.Maximum = SGP.ManagedTextureManager.Instance.GetTextureWidth(tmp.spriteSheetID);

                    SGP.ManagedDirect3D.Instance.Clear(pictureBox1, pictureBox1.BackColor);
                    SGP.ManagedDirect3D.Instance.DeviceBegin();
                    SGP.ManagedDirect3D.Instance.SpriteBegin();
                    {
                        SGP.ManagedTextureManager.Instance.Draw(tmp.spriteSheetID, 0 - offset1.X, 0 - offset1.Y,
                            1, 1, Rectangle.Empty, 0, 0, 0, 0);

                        SGP.ManagedDirect3D.Instance.Sprite.Flush();

                        if (frameList.SelectedIndex != -1)
                        {
                            Frame tmpFrame = tmp.frameList[frameList.SelectedIndex];

                            AnchorX.Maximum = tmpFrame.Rect[0].Width;
                            AnchorY.Maximum = tmpFrame.Rect[0].Height;

                            if (mouseDrag == true)
                            {
                                switch (type)
                                {
                                    case 0:
                                        {
                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(mouseDown.X - offset1.X,
                                                mouseDown.Y - offset1.Y, mousePos.X - mouseDown.X, mousePos.Y - mouseDown.Y), Color.Black, 1);

                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[1].Left - offset1.X,
                                                tmpFrame.Rect[1].Top - offset1.Y, tmpFrame.Rect[1].Width, tmpFrame.Rect[1].Height), Color.Blue, 1);

                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[2].Left - offset1.X,
                                                tmpFrame.Rect[2].Top - offset1.Y, tmpFrame.Rect[2].Width, tmpFrame.Rect[2].Height), Color.Red, 1);
                                        }
                                        break;

                                    case 1:
                                        {
                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[0].Left - offset1.X,
                                                tmpFrame.Rect[0].Top - offset1.Y, tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height), Color.Black, 1);

                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(mouseDown.X - offset1.X,
                                                mouseDown.Y - offset1.Y, mousePos.X - mouseDown.X, mousePos.Y - mouseDown.Y), Color.Blue, 1);

                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[2].Left - offset1.X,
                                                tmpFrame.Rect[2].Top - offset1.Y, tmpFrame.Rect[2].Width, tmpFrame.Rect[2].Height), Color.Red, 1);
                                        }
                                        break;

                                    case 2:
                                        {
                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[0].Left - offset1.X,
                                                tmpFrame.Rect[0].Top - offset1.Y, tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height), Color.Black, 1);

                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[1].Left - offset1.X,
                                                tmpFrame.Rect[1].Top - offset1.Y, tmpFrame.Rect[1].Width, tmpFrame.Rect[1].Height), Color.Blue, 1);

                                            SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(mouseDown.X - offset1.X,
                                                mouseDown.Y - offset1.Y, mousePos.X - mouseDown.X, mousePos.Y - mouseDown.Y), Color.Red, 1);
                                        }
                                        break;
                                }

                            }
                            else
                            {
                                SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[0].Left - offset1.X,
                                    tmpFrame.Rect[0].Top - offset1.Y, tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height), Color.Black, 1);

                                SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[1].Left - offset1.X,
                                tmpFrame.Rect[1].Top - offset1.Y, tmpFrame.Rect[1].Width, tmpFrame.Rect[1].Height), Color.Blue, 1);

                                SGP.ManagedDirect3D.Instance.DrawEmptyRect(new Rectangle(tmpFrame.Rect[2].Left - offset1.X,
                                    tmpFrame.Rect[2].Top - offset1.Y, tmpFrame.Rect[2].Width, tmpFrame.Rect[2].Height), Color.Red, 1);
                            }



                            Rectangle tmpAnchor = new Rectangle((tmpFrame.anchorPoint.X + tmpFrame.Rect[0].Left) - 2 - offset1.X,
                                (tmpFrame.anchorPoint.Y + tmpFrame.Rect[0].Top) - 2 - offset1.Y, 4, 4);

                            SGP.ManagedDirect3D.Instance.DrawRect(tmpAnchor, Color.Green);
                        }
                        
                    }
                    SGP.ManagedDirect3D.Instance.SpriteEnd();
                    SGP.ManagedDirect3D.Instance.DeviceEnd();
                    SGP.ManagedDirect3D.Instance.Present(pictureBox1);

                    // Render Box 2
                    SGP.ManagedDirect3D.Instance.Clear(pictureBox2, pictureBox2.BackColor);
                    SGP.ManagedDirect3D.Instance.DeviceBegin();
                    SGP.ManagedDirect3D.Instance.SpriteBegin();
                    {
                        if (frameList.Items.Count > 0)
                        {
                            Frame tmpFrame = tmp.frameList[frameCount];

                            Rectangle tmpRect = new Rectangle(tmpFrame.Rect[0].Left, tmpFrame.Rect[0].Top,
                                tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height);

                            SGP.ManagedTextureManager.Instance.Draw(tmp.spriteSheetID, 200 - tmpFrame.anchorPoint.X,
                                100 - tmpFrame.anchorPoint.Y, 1, 1, tmpRect, 0, 0, 0, 0);
                        }
                    }
                    SGP.ManagedDirect3D.Instance.SpriteEnd();
                    SGP.ManagedDirect3D.Instance.DeviceEnd();
                    SGP.ManagedDirect3D.Instance.Present(pictureBox2);

                }
                else
                {
                    SGP.ManagedDirect3D.Instance.Clear(pictureBox1, pictureBox1.BackColor);
                    SGP.ManagedDirect3D.Instance.DeviceBegin();
                    SGP.ManagedDirect3D.Instance.SpriteBegin();
                    SGP.ManagedDirect3D.Instance.SpriteEnd();
                    SGP.ManagedDirect3D.Instance.DeviceEnd();
                    SGP.ManagedDirect3D.Instance.Present(pictureBox1);

                    // Render Box 2
                    SGP.ManagedDirect3D.Instance.Clear(pictureBox2, pictureBox2.BackColor);
                    SGP.ManagedDirect3D.Instance.DeviceBegin();
                    SGP.ManagedDirect3D.Instance.SpriteBegin();
                    SGP.ManagedDirect3D.Instance.SpriteEnd();
                    SGP.ManagedDirect3D.Instance.DeviceEnd();
                    SGP.ManagedDirect3D.Instance.Present(pictureBox2);
                }
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.InitialDirectory = workspace;
            dlg.Filter = "Xml Files|*.xml";
            dlg.FilterIndex = 1;
            dlg.DefaultExt = "xml";

            if(DialogResult.OK == dlg.ShowDialog())
            {
                XElement root = new XElement("AnimationList");

                for (int a = 0; a < animationList.Items.Count; ++a)
                {
                    Animation tmpAnimation = (Animation)animationList.Items[a];

                    XElement animation = new XElement("Animation");
                    XElement filename = new XElement("FileName");

                    filename.Add(new XAttribute("playSpeed", tmpAnimation.playSpeed));
                    filename.Add(new XAttribute("looping", tmpAnimation.isLooping == true ? 1 : 0));

                    filename.Value = tmpAnimation.path.Substring(workspace.Length + 1);

                    animation.Add(filename);


                    for (int f = 0; f < tmpAnimation.frameList.Count; ++f)
                    {
                        XElement frame = new XElement("Frame");
                        Frame tmpFrame = tmpAnimation.frameList[f];

                        frame.Add(new XAttribute("x", tmpFrame.Rect[0].Left));
                        frame.Add(new XAttribute("y", tmpFrame.Rect[0].Top));
                        frame.Add(new XAttribute("width", tmpFrame.Rect[0].Width));
                        frame.Add(new XAttribute("height", tmpFrame.Rect[0].Height));
                        frame.Add(new XAttribute("time", tmpFrame.frameDelay));
                        frame.Add(new XAttribute("aPointX", tmpFrame.anchorPoint.X));
                        frame.Add(new XAttribute("aPointY", tmpFrame.anchorPoint.Y));
                        frame.Add(new XAttribute("rx1", tmpFrame.Rect[1].Left));
                        frame.Add(new XAttribute("rx2", tmpFrame.Rect[1].Right));
                        frame.Add(new XAttribute("ry1", tmpFrame.Rect[1].Top));
                        frame.Add(new XAttribute("ry2", tmpFrame.Rect[1].Bottom));
                        frame.Add(new XAttribute("ax1", tmpFrame.Rect[2].Left));
                        frame.Add(new XAttribute("ax2", tmpFrame.Rect[2].Right));
                        frame.Add(new XAttribute("ay1", tmpFrame.Rect[2].Top));
                        frame.Add(new XAttribute("ay2", tmpFrame.Rect[2].Bottom));
                        frame.Value = tmpFrame.eventMessage;

                        animation.Add(frame);
                    }
                    root.Add(animation);
                }
                root.Save(dlg.FileName);
            }
        }

        private void loadAnimationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = workspace;
            dlg.Filter = "Xml Files|*.xml";
            dlg.FilterIndex = 1;

            if (DialogResult.OK == dlg.ShowDialog())
            {
                XElement root = XElement.Load(dlg.FileName);

                IEnumerable<XElement> AnimationList = root.Elements("Animation");

                int aNameIndex = 0;

                foreach(XElement Animation in AnimationList)
                {
                    ++aNameIndex;
                    Animation tmpAnimation = new Animation();

                    tmpAnimation.AnimationName = "Animation" + aNameIndex;
                    tmpAnimation.frameList = new List<Frame>();

                    XElement FileName = Animation.Element("FileName");

                    XAttribute speed = FileName.Attribute("playSpeed");
                    if (speed != null)
                    {
                        tmpAnimation.playSpeed = Convert.ToDecimal(speed.Value);
                    }

                    XAttribute looping = FileName.Attribute("looping");
                    if (looping != null)
                    {
                        int tmp;
                        
                        tmp = Convert.ToInt32(looping.Value);

                        if (tmp == 1)
                        {
                            tmpAnimation.isLooping = true;
                        }
                        else
                        {
                            tmpAnimation.isLooping = false;
                        }
                    }

                    tmpAnimation.FileName = FileName.Value;
                    tmpAnimation.path = workspace + '\\' + tmpAnimation.FileName;
                    tmpAnimation.spriteSheetID = SGP.ManagedTextureManager.Instance.LoadTexture(tmpAnimation.path, 0);

                    IEnumerable<XElement> FrameList = Animation.Elements("Frame");

                    int fNameIndex = 0;
                    foreach (XElement Frame in FrameList)
                    {
                        ++fNameIndex;
                        AnimationTool.Frame tmpFrame = new Frame();
                        tmpFrame.Rect = new RECT[3];
                        tmpFrame.FrameName = "Frame" + fNameIndex;

                        XAttribute x = Frame.Attribute("x");
                        if (x != null)
                        {
                            tmpFrame.Rect[0].Left = Convert.ToInt32(x.Value);
                        }

                        XAttribute y = Frame.Attribute("y");
                        if (y != null)
                        {
                            tmpFrame.Rect[0].Top = Convert.ToInt32(y.Value);
                        }

                        XAttribute width = Frame.Attribute("width");
                        if (width != null)
                        {
                            tmpFrame.Rect[0].Width = Convert.ToInt32(width.Value);
                        }

                        XAttribute height = Frame.Attribute("height");
                        if (height != null)
                        {
                            tmpFrame.Rect[0].Height = Convert.ToInt32(height.Value);
                        }

                        XAttribute time = Frame.Attribute("time");
                        if (time != null)
                        {
                            tmpFrame.frameDelay = Convert.ToDecimal(time.Value);
                        }

                        XAttribute aX = Frame.Attribute("aPointX");
                        if (aX != null)
                        {
                            tmpFrame.anchorPoint.X = Convert.ToInt32(aX.Value);
                        }

                        XAttribute aY = Frame.Attribute("aPointY");
                        if (aY != null)
                        {
                            tmpFrame.anchorPoint.Y = Convert.ToInt32(aY.Value);
                        }

                        XAttribute rx1 = Frame.Attribute("rx1");
                        if (rx1 != null)
                        {
                            tmpFrame.Rect[1].Left = Convert.ToInt32(rx1.Value);
                        }

                        XAttribute rx2 = Frame.Attribute("rx2");
                        if (rx2 != null)
                        {
                            tmpFrame.Rect[1].Right = Convert.ToInt32(rx2.Value);
                        }

                        XAttribute ry1 = Frame.Attribute("ry1");
                        if (ry1 != null)
                        {
                            tmpFrame.Rect[1].Top = Convert.ToInt32(ry1.Value);
                        }

                        XAttribute ry2 = Frame.Attribute("ry2");
                        if (ry2 != null)
                        {
                            tmpFrame.Rect[1].Bottom = Convert.ToInt32(ry2.Value);
                        }

                        XAttribute ax1 = Frame.Attribute("ax1");
                        if (ax1 != null)
                        {
                            tmpFrame.Rect[2].Left = Convert.ToInt32(ax1.Value);
                        }

                        XAttribute ax2 = Frame.Attribute("ax2");
                        if (ax2 != null)
                        {
                            tmpFrame.Rect[2].Right = Convert.ToInt32(ax2.Value);
                        }

                        XAttribute ay1 = Frame.Attribute("ay1");
                        if (ay1 != null)
                        {
                            tmpFrame.Rect[2].Top = Convert.ToInt32(ay1.Value);
                        }

                        XAttribute ay2 = Frame.Attribute("ay2");
                        if (ay2 != null)
                        {
                            tmpFrame.Rect[2].Bottom = Convert.ToInt32(ay2.Value);
                        }

                        tmpFrame.eventMessage = Frame.Value;

                        tmpAnimation.frameList.Add(tmpFrame);   
                    }

                    animationList.Items.Add(tmpAnimation);
                }
            }
        }

        private void loadSpriteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
                OpenFileDialog dlg = new OpenFileDialog();

                dlg.InitialDirectory = workspace;

                if (DialogResult.OK == dlg.ShowDialog())
                {
                    tmp.path = dlg.FileName;
                    tmp.spriteSheetID = SGP.ManagedTextureManager.Instance.LoadTexture(dlg.FileName, 0);
                    animationList.Items[animationList.SelectedIndex] = tmp;
                }
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AnimationGroup.Enabled = false;
            FrameGroup.Enabled = false;

            animationList.Items.Clear();
            frameList.Items.Clear();

            PlaySpeed.Value = 0;
            LoopingCheck.Checked = false;

            ImageTopRect.Value = 0;
            ImageBottomRect.Value = 0;
            ImageLeftRect.Value = 0;
            ImageRightRect.Value = 0;

            ColTopRect.Value = 0;
            ColBottomRect.Value = 0;
            ColLeftRect.Value = 0;
            ColRightRect.Value = 0;

            ActiveTopRect.Value = 0;
            ActiveBottomRect.Value = 0;
            ActiveLeftRect.Value = 0;
            ActiveRightRect.Value = 0;

            AnchorX.Value = 0;
            AnchorY.Value = 0;
            FrameDelay.Value = 0;
            EventMessage.Text = "None";

            resetToolStripMenuItem_Click(sender, e);
        }

        private void setToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();

            if (DialogResult.OK == dlg.ShowDialog())
            {
                workspace = dlg.SelectedPath;
                saveAnimationToolStripMenuItem.Enabled = true;
                openToolStripMenuItem.Enabled = true;
                if(animationList.SelectedIndex != -1)
                    loadToolStripMenuItem.Enabled = true;
            }
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            workspace = "None";
            saveAnimationToolStripMenuItem.Enabled = false;
            openToolStripMenuItem.Enabled = false;
            loadToolStripMenuItem.Enabled = false;
        }

        private void Animations_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                groupBox5.Enabled = true;
                AnimationGroup.Enabled = true;

                if (workspace != "None")
                    loadToolStripMenuItem.Enabled = true;

                Animation a = (Animation)animationList.Items[animationList.SelectedIndex];

                PlaySpeed.Value = a.playSpeed;
                LoopingCheck.Checked = a.isLooping;

                frameList.Items.Clear();
                for (int i = 0; i < a.frameList.Count; ++i)
                    frameList.Items.Add(a.frameList[i]);

                frameList_SelectedIndexChanged(sender, e);
            }
            else
            {
                groupBox5.Enabled = false;
                loadToolStripMenuItem.Enabled = false;
                AnimationGroup.Enabled = false;
                PlaySpeed.Value = 0;
                LoopingCheck.Checked = false;
                frameList.Items.Clear();
            }
        }

        private void frameList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1)
            {
                indexChange = true;
                frameCount = frameList.SelectedIndex;
                if (AnimationGroup.Enabled == true)
                    FrameGroup.Enabled = true;
                Frame f = (Frame)frameList.Items[frameList.SelectedIndex];

                ImageTopRect.Value = f.Rect[0].Top;
                ImageBottomRect.Value = f.Rect[0].Bottom;
                ImageLeftRect.Value = f.Rect[0].Left;
                ImageRightRect.Value = f.Rect[0].Right;

                ColTopRect.Value = f.Rect[1].Top;
                ColBottomRect.Value = f.Rect[1].Bottom;
                ColLeftRect.Value = f.Rect[1].Left;
                ColRightRect.Value = f.Rect[1].Right;

                ActiveTopRect.Value = f.Rect[2].Top;
                ActiveBottomRect.Value = f.Rect[2].Bottom;
                ActiveLeftRect.Value = f.Rect[2].Left;
                ActiveRightRect.Value = f.Rect[2].Right;

                AnchorX.Maximum = f.Rect[0].Width;
                AnchorY.Maximum = f.Rect[0].Height;

                indexChange = false;

                AnchorX.Value = (int)f.anchorPoint.X;
                AnchorY.Value = (int)f.anchorPoint.Y;

                FrameDelay.Value = f.frameDelay;

                EventMessage.Text = f.eventMessage;
                indexChange = false;
            }
            else
            {
                indexChange = false;
                FrameGroup.Enabled = false;
            }

            indexChange = false;
        }

        private void AddAnimation_Click(object sender, EventArgs e)
        {
            Animation tmp = new Animation();
            tmp.spriteSheetID = -1;
            tmp.AnimationName = "Animation " + (animationList.Items.Count + 1);
            tmp.isLooping = false;
            tmp.playSpeed = 1;
            tmp.frameList = new List<Frame>();
            animationList.Items.Add(tmp);
            animationList.SelectedIndex = animationList.Items.Count - 1;

        }

        private void AddFrame_Click(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                Frame tmp = new Frame();
                tmp.FrameName = "Frame " + (frameList.Items.Count + 1);
                tmp.anchorPoint = new Point(0, 0);
                tmp.eventMessage = "None";
                tmp.frameDelay = 0.25M;
                //type = (int)RectType.Image;
                tmp.Rect = new RECT[3];
                frameList.Items.Add(tmp);
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                tmpAnimation.frameList.Add(tmp);

                frameList.SelectedIndex = frameList.Items.Count - 1;

                AnchorX.Maximum = pictureBox1.Width;
                AnchorY.Maximum = pictureBox1.Height;
            }
        }

        private void RemoveAnimation_Click(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                int tmpI = animationList.SelectedIndex;
                animationList.Items.RemoveAt(animationList.SelectedIndex);

                if (tmpI != 0)
                    animationList.SelectedIndex = tmpI - 1;
                else if (animationList.Items.Count > 0)
                    animationList.SelectedIndex = 0;

                for (int a = 0; a < animationList.Items.Count; ++a)
                {
                    Animation tmp = (Animation)animationList.Items[a];

                    tmp.AnimationName = "Animation " + (a + 1);

                    animationList.Items[a] = tmp;
                }
            }
        }

        private void RemoveFrame_Click(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1)
            {
                int tmpI = frameList.SelectedIndex;
                Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
                tmp.frameList.RemoveAt(frameList.SelectedIndex);
                frameList.Items.RemoveAt(frameList.SelectedIndex);

                for (int f = 0; f < tmp.frameList.Count; ++f)
                {
                    Frame tmpFrame = tmp.frameList[f];
                    tmpFrame.FrameName = "Frame " + (f + 1);

                    tmp.frameList[f] = tmpFrame;
                }
                animationList.Items[animationList.SelectedIndex] = tmp;

                if (tmpI != 0)
                    frameList.SelectedIndex = tmpI - 1;
                else if (frameList.Items.Count > 0)
                    frameList.SelectedIndex = 0;
            }
        }

        private void PlaySpeed_ValueChanged(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
                tmp.playSpeed = PlaySpeed.Value;
                animationList.Items[animationList.SelectedIndex] = tmp;
            }
        }

        private void LoopingCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
                tmp.isLooping = LoopingCheck.Checked;
                animationList.Items[animationList.SelectedIndex] = tmp;
            }
        }

        private void ImageButton_Click(object sender, EventArgs e)
        {
                if (type != (int)RectType.Image)
                {
                    type = (int)RectType.Image;
                    groupBox2.Text = "Image Rect";
                    groupBox2.ForeColor = Color.Black;

                    ImageTopRect.Visible = true;
                    ImageBottomRect.Visible = true;
                    ImageLeftRect.Visible = true;
                    ImageRightRect.Visible = true;

                    ColTopRect.Visible = false;
                    ColBottomRect.Visible = false;
                    ColLeftRect.Visible = false;
                    ColRightRect.Visible = false;

                    ActiveTopRect.Visible = false;
                    ActiveBottomRect.Visible = false;
                    ActiveLeftRect.Visible = false;
                    ActiveRightRect.Visible = false;
                }
        }

        private void CollsionButton_Click(object sender, EventArgs e)
        {

                if (type != (int)RectType.Collision)
                {
                    type = (int)RectType.Collision;
                    groupBox2.Text = "Collision Rect";
                    groupBox2.ForeColor = Color.Blue;
                    CollsionButton.ForeColor = Color.Blue;

                    ImageTopRect.Visible = false;
                    ImageBottomRect.Visible = false;
                    ImageLeftRect.Visible = false;
                    ImageRightRect.Visible = false;

                    ColTopRect.Visible = true;
                    ColBottomRect.Visible = true;
                    ColLeftRect.Visible = true;
                    ColRightRect.Visible = true;

                    ActiveTopRect.Visible = false;
                    ActiveBottomRect.Visible = false;
                    ActiveLeftRect.Visible = false;
                    ActiveRightRect.Visible = false;
                }
        }

        private void ActiveButton_Click(object sender, EventArgs e)
        {
            
                if (type != (int)RectType.Active)
                {
                    type = (int)RectType.Active;
                    groupBox2.Text = "Active Rect";
                    groupBox2.ForeColor = Color.Red;

                    ImageTopRect.Visible = false;
                    ImageBottomRect.Visible = false;
                    ImageLeftRect.Visible = false;
                    ImageRightRect.Visible = false;

                    ColTopRect.Visible = false;
                    ColBottomRect.Visible = false;
                    ColLeftRect.Visible = false;
                    ColRightRect.Visible = false;

                    ActiveTopRect.Visible = true;
                    ActiveBottomRect.Visible = true;
                    ActiveLeftRect.Visible = true;
                    ActiveRightRect.Visible = true;
                }
        }

        private void TopRect_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                if(type == (int)RectType.Image)
                    tmp.Rect[type].Top = (int)ImageTopRect.Value;
                else if (type == (int)RectType.Collision)
                    tmp.Rect[type].Top = (int)ColTopRect.Value;
                else
                    tmp.Rect[type].Top = (int)ActiveTopRect.Value;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void LeftRect_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                if (type == (int)RectType.Image)
                    tmp.Rect[type].Left = (int)ImageLeftRect.Value;
                else if (type == (int)RectType.Collision)
                    tmp.Rect[type].Left = (int)ColLeftRect.Value;
                else
                    tmp.Rect[type].Left = (int)ActiveLeftRect.Value;
                
                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void BottomRect_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                if (type == (int)RectType.Image)
                    tmp.Rect[type].Bottom = (int)ImageBottomRect.Value;
                else if (type == (int)RectType.Collision)
                    tmp.Rect[type].Bottom = (int)ColBottomRect.Value;
                else
                    tmp.Rect[type].Bottom = (int)ActiveBottomRect.Value;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void RightRect_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                if (type == (int)RectType.Image)
                    tmp.Rect[type].Right = (int)ImageRightRect.Value;
                else if (type == (int)RectType.Collision)
                    tmp.Rect[type].Right = (int)ColRightRect.Value;
                else
                    tmp.Rect[type].Right = (int)ActiveRightRect.Value;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void AnchorX_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                tmp.anchorPoint.X = (int)AnchorX.Value;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void AnchorY_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                tmp.anchorPoint.Y = (int)AnchorY.Value;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void FrameDelay_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                tmp.frameDelay = FrameDelay.Value;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;

                splitContainer2.Panel2.Refresh();
                pictureBox2.Invalidate();
            }
        }

        private void EventMessage_TextChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && animationList.SelectedIndex != -1 && !indexChange)
            {
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = tmpAnimation.frameList[frameList.SelectedIndex];

                tmp.eventMessage = EventMessage.Text;

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
        //    if (animationList.SelectedIndex != -1)
        //    {
        //        Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
            

        //        pictureBox1.Show();
                
        //        if(frameList.SelectedIndex != -1)
        //        {
        //            Frame tmpFrame = tmp.frameList[frameList.SelectedIndex];
        //            Pen imagePen = new Pen(Color.Black, 0.5f);
        //            Pen colPen = new Pen(Color.Blue, 0.5f);
        //            Pen activePen = new Pen(Color.Red, 0.5f);
                   
                    
        //            e.Graphics.DrawRectangle(imagePen, tmpFrame.Rect[0].Left, tmpFrame.Rect[0].Top,
        //                tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height);

        //            e.Graphics.DrawRectangle(colPen, tmpFrame.Rect[1].Left, tmpFrame.Rect[1].Top,
        //                tmpFrame.Rect[1].Width, tmpFrame.Rect[1].Height);

        //            e.Graphics.DrawRectangle(activePen, tmpFrame.Rect[2].Left, tmpFrame.Rect[2].Top,
        //                tmpFrame.Rect[2].Width, tmpFrame.Rect[2].Height);
                    
        //        }

        //    }
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            //if (animationList.SelectedIndex != -1 && frameList.Items.Count > 0)
            //{
            //    Animation tmp = (Animation)animationList.Items[animationList.SelectedIndex];
            //    Frame tmpFrame = tmp.frameList[frameCount];

            //    Rectangle tmpRect = new Rectangle(tmpFrame.Rect[0].Left, tmpFrame.Rect[0].Top,
            //    tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height);

            //    e.Graphics.DrawImage(tmp.spriteSheetID, 50, 50, tmpRect, GraphicsUnit.Pixel);


                //pictureBox2.Image = tmp.spriteSheetID;

                //pictureBox2.Width = tmpRect.Width;
                //pictureBox2.Height = tmpRect.Height;
                //pictureBox2.Location = new Point(tmpRect.Left, tmpRect.Top);
                ////pictureBox2. = tmpRect.Left;
                //pictureBox2.Show();

                //Pen imagePen = new Pen(Color.Black, 0.5f);

                //e.Graphics.DrawRectangle(imagePen, tmpFrame.Rect[0].Left, tmpFrame.Rect[0].Top,
                       // tmpFrame.Rect[0].Width, tmpFrame.Rect[0].Height);
                
            //}
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (frameList.SelectedIndex != -1)
                {
                    Frame tmp = (Frame)frameList.Items[frameList.SelectedIndex];
                    if ((e.X + offset1.X - tmp.Rect[0].Left) <= AnchorX.Maximum && (e.X + offset1.X - tmp.Rect[0].Left) >= AnchorX.Minimum)
                    {
                        tmp.anchorPoint.X = e.X + offset1.X - tmp.Rect[0].Left;
                    }
                    else if ((e.X - tmp.Rect[0].Left) > AnchorX.Maximum)
                    {
                        tmp.anchorPoint.X = (int)AnchorX.Maximum;
                    }
                    else
                    {
                        tmp.anchorPoint.X = (int)AnchorX.Minimum;
                    }

                    if (((e.Y + offset1.Y) - tmp.Rect[0].Top) <= AnchorY.Maximum && ((e.Y + offset1.Y) - tmp.Rect[0].Top) >= AnchorY.Minimum)
                    {
                        tmp.anchorPoint.Y = e.Y + offset1.Y - tmp.Rect[0].Top;
                    }
                    else if (((e.Y + offset1.Y) - tmp.Rect[0].Top) > AnchorY.Maximum)
                    {
                        tmp.anchorPoint.Y = (int)AnchorY.Maximum;
                    }
                    else
                    {
                        tmp.anchorPoint.Y = (int)AnchorY.Minimum;
                    }
                    indexChange = false;

                    //Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                    //tmpAnimation.frameList.Add(tmp);
                    frameList.Items[frameList.SelectedIndex] = tmp;
                }
            }
        }

        private void PauseButton_Click(object sender, EventArgs e)
        {
            animationTime.Stop();
            groupBox5.Enabled = true;
            groupBox6.Enabled = true;
            AnimationGroup.Enabled = true;
            FrameGroup.Enabled = true;
            ResetButton.Enabled = true;
            NextFrameButton.Enabled = true;
            PrevFrameButton.Enabled = true;
        }

        private void PlayButton_Click(object sender, EventArgs e)
        {
            if (frameList.Items.Count > 0)
            {
                if (frameCount == 0)
                {
                    frameList.SelectedIndex = 0;
                    Frame tmp = (Frame)frameList.Items[0];
                    animationTime.Enabled = true;
                    animationTime.Interval = (int)(1000 * tmp.frameDelay);
                    animationTime.Start();
                }
                else
                {
                    frameList.SelectedIndex = frameCount;
                    animationTime.Start();
                }

                ResetButton.Enabled = false;
                NextFrameButton.Enabled = false;
                PrevFrameButton.Enabled = false;
                groupBox5.Enabled = false;
                groupBox6.Enabled = false;
                AnimationGroup.Enabled = false;
                FrameGroup.Enabled = false;
            }
        }

        private void ResetButton_Click(object sender, EventArgs e)
        {
            frameList.SelectedIndex = 0;
            frameCount = 0;
            animationTime.Stop();
        }

        private void NextFrameButton_Click(object sender, EventArgs e)
        {
            if (frameCount >= frameList.Items.Count - 1)
            {
                frameCount = 0;
                frameList.SelectedIndex = frameCount;

            }
            else
            {
                ++frameCount;
                frameList.SelectedIndex = frameCount;
            }
        }

        private void PrevFrameButton_Click(object sender, EventArgs e)
        {
            if (frameCount == 0)
            {
                frameCount = frameList.Items.Count - 1;
                frameList.SelectedIndex = frameCount;
            }
            else
            {
                --frameCount;
                frameList.SelectedIndex = frameCount;
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (frameList.SelectedIndex != -1 && e.Button == MouseButtons.Left)
            {
                mouseDrag = true;
                mouseDown.X = e.Location.X + offset1.X;
                mouseDown.Y = e.Location.Y + offset1.Y;
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (frameList.SelectedIndex != -1 && e.Button == MouseButtons.Left)
            {
                mouseDrag = false;
                Animation tmpAnimation = (Animation)animationList.Items[animationList.SelectedIndex];
                Frame tmp = (Frame)frameList.Items[frameList.SelectedIndex];
                mouseUp.X = e.Location.X + offset1.X;
                mouseUp.Y = e.Location.Y + offset1.Y;

                if (mouseDown.X < mouseUp.X)
                {
                    tmp.Rect[type].Left = mouseDown.X;
                    tmp.Rect[type].Right = mouseUp.X;
                }
                else
                {
                    tmp.Rect[type].Left = mouseUp.X;
                    tmp.Rect[type].Right = mouseDown.X;
                }
                if (mouseDown.Y < mouseUp.Y)
                {
                    tmp.Rect[type].Top = mouseDown.Y;
                    tmp.Rect[type].Bottom = mouseUp.Y;
                }
                else
                {
                    tmp.Rect[type].Top = mouseUp.Y;
                    tmp.Rect[type].Bottom = mouseDown.Y;
                }

                if (tmp.Rect[type].Right > ImageRightRect.Maximum)
                    tmp.Rect[type].Right = (int)ImageRightRect.Maximum;

                if (tmp.Rect[type].Left < 0)
                    tmp.Rect[type].Left = 0;

                if (tmp.Rect[type].Bottom > ImageBottomRect.Maximum)
                    tmp.Rect[type].Bottom = (int)ImageBottomRect.Maximum;

                if (tmp.Rect[type].Top < 0)
                    tmp.Rect[type].Top = 0;

                if (type == (int)RectType.Image)
                {
                    tmp.anchorPoint.X = 0;
                    tmp.anchorPoint.Y = 0;
                }

                tmpAnimation.frameList[frameList.SelectedIndex] = tmp;
                frameList.Items[frameList.SelectedIndex] = tmp;
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            mousePos.X = e.Location.X + offset1.X;
            mousePos.Y = e.Location.Y + offset1.Y;
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            Render();
        }
    }
}
